package yxy.game.pm2.active.module;

import org.joda.time.DateTime;
import yxy.apple.util.PubSub.MethodSubscriber;
import yxy.apple.util.PubSub.SubscriptionMethod;
import yxy.game.pm2.bean.Hero;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.bean.pubsub.HeroStarPublisher;
import yxy.game.pm2.bean.pubsub.HeroStarPublisher.HeroStarSubscription;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;

public class ActiveSubscriber_养成礼包 extends MethodSubscriber {

    static private ActiveSubscriber_养成礼包 instance;

    public static ActiveSubscriber_养成礼包 getInstance() {
        if (instance == null) {
            instance = new ActiveSubscriber_养成礼包();
            instance.init();
        }
        return instance;
    }

    private void init() {
        HeroStarPublisher.getInstance().subscribe(this);
    }

    private ActiveSubscriber_养成礼包() {
    }

    @SubscriptionMethod(Type = HeroStarSubscription.class)
    public void receive(HeroStarSubscription subscription) {
        String playerCode = subscription.getPlayerCode();
        Hero hero = subscription.getHero();
        CCReason reason = subscription.getReason();

        int star = hero.getStar();
        if ((star == ActiveModule_养成礼包.type_star_5 && reason == CCReason.招募武将)
                || (star == ActiveModule_养成礼包.type_star_6 && reason == CCReason.武将培养)) {
            ActiveModule_养成礼包 am = ActiveModule_养成礼包.get(playerCode);
            if (am == null) {
                return;
            }
            //当天只发送一次
            if (am.getStartTime() == null || isNextDay(am)) {
                am.setStartTime(DateTime.now());
                am.set();
                am.createDevelopGiftPackage(star);
            }
        }

    }

    //判断是否下一天
    public Boolean isNextDay(ActiveModule_养成礼包 am) {
        Date date = am.getStartTime().toDate();
        Calendar instance = Calendar.getInstance();
        instance.setTime(date);
        int year = instance.get(Calendar.YEAR);
        int month = instance.get(Calendar.MONTH) + 1; //当前月
        int day = instance.get(Calendar.DAY_OF_MONTH);
        LocalDate startDate = LocalDate.of(year, month, day);
        long betweenDay = ChronoUnit.DAYS.between(startDate, LocalDate.now());
        return betweenDay >= 1;
    }

}
